﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TableProto;
using WCBG.ToolsForUnity.Tools;
using WCBG.ToolsForUnity.Extension;
using DG.Tweening;

/// <summary>
/// 英语颜色 填字母游戏
/// </summary>
public class FillLetterGameWindow : SingletonBaseWindow<FillLetterGameWindow>
{

    #region ui property

    public Button _Btn_Return { get; set; }
    public RectTransform _LetterImg { get; set; }
    public RectTransform _Letter { get; set; }
    public RectTransform _LetterGroup { get; set; }
    public RectTransform _LetterLeft { get; set; }
    public RectTransform _LetterRight { get; set; }
    public RectTransform _LetterImgParent { get; set; }
    public RectTransform _DuoduoStartPoint { get; set; }
    public RectTransform _DuoduoEndPoint { get; set; }
    public RectTransform _LediImg { get; set; }


    #endregion

    private const string TEXTURE_BASE_PATH = EnglishColoursPath.englishColorLetterTexturePath;
    private const float HINT_INTERVAL_TIM = 15;

    private FillLetterHolder m_dragHolder;
    private Vector3 m_dragOffset;
    private bool isLockInput;
    private int hintSeq;

    private EnglishColoursInfo m_info;
    private System.Action fillLetterCallback;
    private System.Action<bool> completeCallback;


    private List<GameObject> m_letterObjList = new List<GameObject>();
    private List<FillLetterHolder> m_letterList = new List<FillLetterHolder>();
    private List<FillLetterHolder> m_letterImageList = new List<FillLetterHolder>();


    protected override void OnOpen(params object[] paramArray)
    {
        _LediImg.gameObject.SetActive(false);
        _LetterLeft.SetActive(false);
        _LetterRight.SetActive(false);
        _DuoduoStartPoint.SetActive(false);
        _DuoduoEndPoint.SetActive(false);
    }

    protected override void OnClose()
    {
        ClearLetter();
    }

    protected override void AddListeners()
    {
        _Btn_Return.onClick.AddListener(OnButtonReturnClick);
        FEasyInput.AddEvent(EEasyInputType.OnDown, OnDown);
        FEasyInput.AddEvent(EEasyInputType.OnHover, OnHover);
        FEasyInput.AddEvent(EEasyInputType.OnUp, OnUp);
        hintSeq = InputTimerManager.Instance.AddTimerNoInput(HINT_INTERVAL_TIM, true, OnHintEvent);
    }

    protected override void RemoveListensers()
    {
        _Btn_Return.onClick.RemoveAllListeners();
        FEasyInput.RemoveEvent(EEasyInputType.OnDown, OnDown);
        FEasyInput.RemoveEvent(EEasyInputType.OnHover, OnHover);
        FEasyInput.RemoveEvent(EEasyInputType.OnUp, OnUp);
        InputTimerManager.Instance.RemoveTimerNoInput(hintSeq);
    }


    private void OnDown()
    {
        if (m_dragHolder != null)
        {
            m_dragHolder.transform.DORotate(Vector3.zero, .5f).SetEase(Ease.Linear);
        }
    }

    private void OnHover()
    {
        if (m_dragHolder != null)
        {
            Vector3 mousePos = Input.mousePosition;
            if (mousePos.x >= Screen.width * .06f && mousePos.x < Screen.width * (1 - .06f) && mousePos.y >= Screen.height * .12f && mousePos.y < Screen.height * (1 - .12f))
            {
                Vector3 to = FUGUITool.ScreenPointToUGUIPoint(WindowManager.Instance.canvas, Input.mousePosition);
                m_dragHolder.transform.position = to + m_dragOffset;
            }
        }
    }

    private void OnUp()
    {
        if (m_dragHolder != null)
        {
            CheckDragState();
            m_dragHolder = null;
        }
    }

    private void OnHintEvent(int seq)
    {
        foreach (FillLetterHolder holder in m_letterImageList)
        {
            if (!holder.isComplete)
            {
                holder.PlayHintAnim();
                this.PlayAudioEx(StudyAudioName.t_41016);
                break;
            }
        }
    }

    private void CheckDragState()
    {
        foreach (FillLetterHolder holder in m_letterList)
        {
            if (!holder.isComplete && holder.letter == m_dragHolder.letter)
            {
                float dis = Vector3.Distance(holder.letterLinePos, m_dragHolder.transform.position);
                if (dis < 10f)
                {
                    this.PlayAudioEx(StudyAudioName.t_41015);
                    holder.UpdateCompleteState(true);
                    m_dragHolder.PlayCompleteAnim(holder.transform, holder.letterLinePos);

                    m_letterList.Remove(holder);
                    if (m_letterList.Count == 0)
                    {
                        this.AddTimerEx(1f, () => {
                            GameAudioSource audio = null;
                            audio = this.PlayEnglishColoursAudioEx(m_info.secondWordAudio);
                            this.AddTimerEx(audio.Length + 0.5f, () => {
                                if (fillLetterCallback != null)
                                {
                                    fillLetterCallback();
                                }
                            });
                        });
                    }
                    break;
                }
            }
        }

        if (!m_dragHolder.isComplete)
        {
            //m_dragHolder.MoveBackStartPos();
            m_dragHolder.transform.DORotate(m_dragHolder.letterStartRotation.eulerAngles, .5f).SetEase(Ease.Linear);
        }
        m_dragHolder = null;
    }

    private void StartFillLetter(EnglishColoursInfo info, System.Action callback)
    {
        fillLetterCallback = callback;
        ClearLetter();

        char[] arr = info.word.ToCharArray();
        string[] audioArr = info.wordAudioArray.Split(';');
        //arr = new char[26] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
        for (int i = 0; i < arr.Length; i++)
        {
            string str = arr[i].ToString().ToLower();
            GameObject go = GameObject.Instantiate(_Letter.gameObject, _LetterGroup);
            go.SetActive(true);
            FillLetterHolder holder = go.AddComponentEx<FillLetterHolder>();
            holder.Initialize(str, audioArr[i], true);
            m_letterObjList.Add(go);
            m_letterList.Add(holder);

            GameObject imgGo = GameObject.Instantiate(_LetterImg.gameObject, go.transform);
            imgGo.SetActive(true);
            imgGo.transform.position = holder.letterLinePos;
            imgGo.name = str;
            holder = imgGo.AddComponentEx<FillLetterHolder>();
            holder.Initialize(str, audioArr[i], false);
            m_letterImageList.Add(holder);

            imgGo.AddComponentEx<UIInputHandler>().OnDown += ()=> {
                OnImgDown(imgGo.GetComponent<Image>());
            };
        }

        this.AddTimerEx(2.0f, ()=> {

            _LediImg.gameObject.SetActive(true);
            _LediImg.position = _DuoduoStartPoint.position;
            _LediImg.DOMove(_DuoduoEndPoint.position, 1.3f).SetEase(Ease.Linear).OnComplete(()=> {
                _LediImg.gameObject.SetActive(false);
            });
            this.AddTimerEx(0.15f, MixLetter);
        });
    }

    private void MixLetter()
    {
        this.PlayAudioEx(StudyAudioName.t_41006);
        

        Vector3 dir = _LetterLeft.position - _LetterRight.position;
        List<Vector3> randomPos = new List<Vector3>();
        for (int i = 0; i < m_letterImageList.Count; i++)
        {

           Vector3 pos = _LetterRight.position + new Vector3(Random.Range(0, dir.x), Random.Range(0, dir.y), 0);
           randomPos.Add(pos);
        }
        int count = m_letterImageList.Count;
        for (int i = 0; i < count; i++)
        {
            int index = i;
            int randomIndex = Random.Range(0, randomPos.Count);
            Vector3 toPos = randomPos[randomIndex];

            this.AddTimerEx(0.15f * index, () => {
                m_letterImageList[count - 1 - index].transform.SetParent(_LetterImgParent);
                m_letterImageList[count - 1 - index].MixToPos(toPos);
            });
            randomPos.RemoveAt(randomIndex);
        }
    }

    private void OnImgDown(Image img)
    {
        m_dragHolder = img.gameObject.GetComponent<FillLetterHolder>();
        if (m_dragHolder.isComplete)
        {
            m_dragHolder = null;
            return;
        }
        this.PlayEnglishColoursAudioEx(m_dragHolder.letterAudio);
        Vector3 to = FUGUITool.ScreenPointToUGUIPoint(WindowManager.Instance.canvas, Input.mousePosition);
        m_dragOffset = m_dragHolder.transform.position - to;
    }



    #region uievent

    private void OnButtonReturnClick()
    {
        if (isLockInput)
            return;
        isLockInput = true;

        EnglishColorManager.Instance.StopCurrentGame();

    }

    #endregion



    public void StartGame(EnglishColoursInfo info, System.Action<bool> callback)
    {
        if (info == null)
        {
            Debug.LogError("Fill info is null!");
            if (callback != null)
                callback(false);
            return;
        }

        m_info = info;
        completeCallback = callback;
        isLockInput = false;

        StartFillLetter(info, () => {
            if (completeCallback != null)
                completeCallback(true);
        });
    }
    
    private Sprite LoadSprite(string name)
    {
        return Res.LoadSprite(TEXTURE_BASE_PATH + name);
    }

    private void ClearLetter()
    {
        foreach (GameObject go in m_letterObjList)
        {
            GameObject.Destroy(go);
        }
        foreach (FillLetterHolder holder in m_letterImageList)
        {
            GameObject.Destroy(holder.gameObject);
        }
        m_letterObjList.Clear();
        m_letterList.Clear();
        m_letterImageList.Clear();
    }


}
